package com.rabbiter.si.controller;

import com.rabbiter.si.common.ExcelUtils;
import com.rabbiter.si.entity.ImportResult;
import com.rabbiter.si.entity.StudentCourseTeacher;
import com.rabbiter.si.service.GradeService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/api/grades")
public class GradeController {

    @Autowired
    private GradeService gradeService;

    // 导入学生课程教师信息
    @PostMapping("/import")
    public ResponseEntity<?> importGrades(@RequestParam("file") MultipartFile file) {
        ImportResult result = gradeService.importGrades(file);

        Map<String, Object> response = new HashMap<>();
        response.put("addedCount", result.getAddedCount());
        response.put("updatedCount", result.getUpdatedCount());
        response.put("errorCount", result.getErrors().size());
        response.put("errors", result.getErrors());

        if (result.isFullySuccessful()) {
            response.put("success", true);
            response.put("message", "导入成功，共处理 " + (result.getAddedCount() + result.getUpdatedCount()) + " 条记录");
        } else {
            response.put("success", false);
            response.put("message", "导入部分成功，存在 " + result.getErrors().size() + " 条错误记录");
        }

        return ResponseEntity.ok(response);
    }

    // 导出学生课程教师信息
    @GetMapping("/export")
    public void exportGrades(HttpServletResponse response) {
        try {
            // 获取数据
            List<StudentCourseTeacher> sctList = gradeService.getAllStudentCourseTeacher();

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("学生课程教师信息.xlsx", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);

            // 生成Excel并写入响应流
            ByteArrayInputStream inputStream = ExcelUtils.exportToExcel(sctList);
            inputStream.transferTo(response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("导出失败: " + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}